package com.banyou.banyou.main.info;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.banyou.banyou.MainApplication;
import com.banyou.banyou.R;
import com.banyou.banyou.adapter.IllnessGridAdapter;
import com.banyou.banyou.adapter.PicAdapter;
import com.banyou.banyou.base.BaseActivity;
import com.banyou.banyou.bean.main.info.AccompingInfoBean;
import com.banyou.banyou.customviews.RadioGroupEx;
import com.banyou.banyou.customviews.ScrollGridView;
import com.banyou.banyou.order.DoOdrderActivity;
import com.banyou.banyou.picture.PictureActivity;
import com.banyou.banyou.util.FontDisplayUtil;
import com.banyou.banyou.util.GlideUtil;
import com.banyou.banyou.util.ShowToast;
import com.banyou.banyou.webutils.ProgressSubscriber;
import com.socks.library.KLog;
import com.squareup.timessquare.CalendarPickerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ----------Dragon be here!----------/
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃代码无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * 类描述：
 * 创建人：Random
 * 修改时间：
 * 修改备注：
 */

public class InfoActivity extends BaseActivity<InfoPresenter> implements InfoContract.View {

    @BindView(R.id.main_img)
    ImageView mMainImg;
    @BindView(R.id.name)
    TextView mName;
    @BindView(R.id.sex)
    TextView mSex;
    @BindView(R.id.star_content)
    LinearLayout mStarContent;
    @BindView(R.id.head_content)
    RelativeLayout mHeadContent;
    @BindView(R.id.scroll_grid)
    ScrollGridView mScrollGrid;
    //    @BindView(R.id.date_btn)
//    Button mDateBtn;
    @BindView(R.id.main_btn)
    Button mMainBtn;
    @BindView(R.id.time_content)
    RadioGroupEx mTimeContent;
    @BindView(R.id.back_btn)
    ImageView mBackBtn;
    @BindView(R.id.other_information)
    TextView mOtherInformation;
    @BindView(R.id.my_image)
    TextView mMyImage;
    @BindView(R.id.age)
    TextView mAge;
    @BindView(R.id.short_msg)
    TextView mShortMsg;

    private long mDataTime = 86400000;
    private AlertDialog mAlertDialog;
    private ArrayList<String> mSelectedDays = new ArrayList<>();
    private List<String> mUrls;
    private IllnessGridAdapter mGridAdapter;
    private Bundle mBundle = new Bundle();
    private double mReward;
    private int mUserId;

    @Override
    protected InfoPresenter initPresenter() {
        return new InfoPresenter();
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_info;
    }

    @Override
    protected View initLayoutView() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter.initPresenter(this, new InfoModel());
        ButterKnife.bind(this);
        mUrls = new ArrayList<>();
        mGridAdapter = new IllnessGridAdapter(mUrls, this);
        mScrollGrid.setAdapter(mGridAdapter);
        mScrollGrid.setOnItemClickListener(mOnItemClickListener);
        mPresenter.getData(getIntent().getIntExtra("userId", 0) + ""); //TODO UserId
        if (getSharedPreference().getString("userType", "1").equals("2")) {
            mMainBtn.setVisibility(View.GONE);
        }
    }

    /**
     * 图片点击跳转大图页面
     */
    AdapterView.OnItemClickListener mOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(InfoActivity.this, PictureActivity.class);
            Bundle bundle = new Bundle();
            bundle.putStringArrayList("list", (ArrayList<String>) mUrls);
            bundle.putInt("position", position);
            intent.putExtra("list", bundle);
            startActivity(intent);
        }
    };

    /**
     * 初始化日历
     */
    private void initCalendar() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        Calendar nextYear = Calendar.getInstance();
        nextYear.add(Calendar.MONTH, 1);
        View view = LayoutInflater.from(this).inflate(R.layout.activity_info_dialog, null);
        final CalendarPickerView calendar = (CalendarPickerView) view.findViewById(R.id.calendar_view);
        Date today = new Date();
        final List<Date> mList = new ArrayList<>();
        //循环选择可选日期
        //TODO 按真实日期来
        for (int i = 0; i < 5; i++) {
            Date highlight = new Date();
            highlight.setTime(highlight.getTime() + mDataTime * i);
            mList.add(highlight);
        }
        calendar.init(today, nextYear.getTime()).inMode(CalendarPickerView.SelectionMode.MULTIPLE);
        calendar.clearHighlightedDates();
        calendar.highlightDates(mList);
        //使可选日期可以被选择，不可选日期不会被选择
        calendar.setDateSelectableFilter(new CalendarPickerView.DateSelectableFilter() {
            @Override
            public boolean isDateSelectable(Date date) {
                SimpleDateFormat sdf = new SimpleDateFormat("dd");
                String format1 = sdf.format(date);

                for (int i = 0; i < mList.size(); i++) {
                    if (format1.equals(sdf.format(mList.get(i)))) {
                        return true;
                    }
                }

                return false;
            }
        });
        //设定点击到不可选日期时，弹出的提示
        calendar.setOnInvalidDateSelectedListener(new CalendarPickerView.OnInvalidDateSelectedListener() {
            @Override
            public void onInvalidDateSelected(Date date) {
                Toast.makeText(MainApplication.getContext(), "请选择可选绿色的日期", Toast.LENGTH_SHORT).show();
            }
        });
        //设置一个确定按钮
        builder.setView(view)
                .setCancelable(true)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mAlertDialog.dismiss();
                    }
                });
        mAlertDialog = builder.create();
        //Dialog窗口Dismiss的时候
        mAlertDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                List<Date> selectedDates = calendar.getSelectedDates();
                if (selectedDates.size() != 0) {
                    //在这里添加一行文字
                    TextView textView = new TextView(InfoActivity.this);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    textView.setLayoutParams(params);
                    textView.setText("你选择的预约日期：");
                    mTimeContent.addView(textView);
                }
                //循环已选择日期，平铺展示在界面上
                mSelectedDays.clear();
                for (int i = 0; i < selectedDates.size(); i++) {
                    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
                    String format = sdf.format(selectedDates.get(i));
                    View view = (LayoutInflater.from(InfoActivity.this).inflate(R.layout.date_btn, null));
                    TextView textView = (TextView) view.findViewById(R.id.date_text);
                    textView.setText(format);
                    mSelectedDays.add(format);
                    mTimeContent.addView(view);
                }
            }
        });
        //弹出dialog的时候，清空已选日期
        mAlertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                mTimeContent.removeAllViews();
            }
        });
        mAlertDialog.show();

    }

    @Override
    protected String pageName() {
        return "详情页";
    }

    @OnClick({R.id.main_btn, R.id.back_btn})
    public void onClick(View view) {
        switch (view.getId()) {
//            case R.id.date_btn:
////                initCalendar();//初始化日历
//                break;
            case R.id.main_btn:
                Intent intent = new Intent(this, DoOdrderActivity.class);
                intent.putStringArrayListExtra("list", mSelectedDays);
                intent.putExtra("bundle", mBundle);
                intent.putExtra("userId", mUserId);
                intent.putExtra("reward", mReward);
                startActivity(intent);
                break;
            case R.id.back_btn:
                InfoActivity.this.finish();
                break;
        }
    }

    /**
     * 获取数据成功
     *
     * @param bean
     */
    @Override
    public void getDataSuccess(AccompingInfoBean bean) {
        mUrls.clear();
        if (bean.getUSER_PHOTO_ALUM() != null) {
            mUrls.addAll(bean.getUSER_PHOTO_ALUM());
        }
        mUserId = bean.getUSER_ID();
        mGridAdapter.notifyDataSetChanged();
        GlideUtil.circleLocalLoad(this, bean.getPORTAL_IMAG_PATH(), mMainImg);
        mAge.setText("年龄：" +( bean.getAGE()==null?"待补充":bean.getAGE()));
        mName.setText("姓名：" + (bean.getUSER_NAME()==null?"待补充":bean.getUSER_NAME()));
        mShortMsg.setText("陪游景点：" + (bean.getREMARKS()==null?"待补充":bean.getREMARKS()));
        String height = bean.getUSER_HEIGHT() == null ? "待补充" : bean.getUSER_HEIGHT()+"cm";
        String weight = bean.getUSER_WEIGHT() == null ? "待补充" : bean.getUSER_WEIGHT()+"kg";
        String degree = bean.getUSER_DEGREE() == null ? "待补充" : bean.getUSER_DEGREE();
        String marrage = bean.getUSER_MARRAGE() == null ? "待补充" : bean.getUSER_MARRAGE();
        String language = bean.getUSER_LANGUAGE() == null ? "待补充" : bean.getUSER_LANGUAGE();
        String star = bean.getUSER_STAR() == null ? "待补充" : bean.getUSER_STAR();
        String job = bean.getUSER_JOB() == null ? "待补充" : bean.getUSER_JOB();
        mOtherInformation.setText("我的身高：" + height + "\n我的体重：" + weight +
                "\n我的学历：" + degree + "\n我的工作：" + job + "\n我的婚姻：" +marrage+
        "\n我的语言："+language+"\n我的星座："+star);
        if (bean.getSEX().equals("M")) {
            mSex.setText("性别：男");
            mSex.setCompoundDrawables(null, null, getResources().getDrawable(R.drawable.boy), null);
        } else {
            mSex.setText("性别：女");
            mSex.setCompoundDrawables(null, null, getResources().getDrawable(R.drawable.girl), null);
        }
        mSex.setCompoundDrawablePadding(FontDisplayUtil.dip2px(5));
        mStarContent.removeAllViews();
        for (int i = 0; i < bean.getLEVEL(); i++) {
            ImageView imageView = new ImageView(this);
            imageView.setLayoutParams(new LinearLayoutCompat.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            imageView.setImageResource(R.drawable.star);
            mStarContent.addView(imageView);
        }
        mBundle.putString("name", bean.getUSER_NAME());
        mBundle.putString("image", bean.getPORTAL_IMAG_PATH());
        mBundle.putString("age", bean.getAGE());
        mBundle.putString("sex", bean.getSEX());
        mBundle.putString("shortMsg", bean.getREMARKS());
        mBundle.putInt("level", bean.getLEVEL());
        mReward = bean.getREWARD();
    }

    /**
     * 获取数据失败
     */
    @Override
    public void getDataFail(Throwable e) {
        if (e instanceof ProgressSubscriber.ReturnCodeErrorException) {
            ShowToast.showToast(((ProgressSubscriber.ReturnCodeErrorException) e).getMsg());
        } else {
            ShowToast.showToast("请求数据失败");
        }
    }

}
